if (typeof Promise === 'undefined') {
    Promise = require("./es6-promise.min.js").Promise;
}
const EventDispatcher = require("./EventDispatcher.js");
const config = require('../config.js');
// const SocketEvent = {
//   FOODS_DATA: 2,//菜品数据到达
//   NEW_FOOD: 3,//有人点菜了,
//   SUBMIT: 4,//提交订单
//   LOCK: 5,//锁定
//   TIMEOUT: 6,//超时
// }
var mid = wx.getStorageSync('mid');
var SEvent = {};
var status = 0;
var socketData = null;
var heartId = 0;
class Socket extends EventDispatcher {
    constructor() {
        super();
        let ps = getCurrentPages()
        this.source = ps[ps.length - 1]
    }

    //打开socke链接
    open(data) {
        let ps = getCurrentPages();
        let current = ps[ps.length - 1];

        socketData = data;

        if (wx.canIUse("showLoading")) {
            wx.showLoading({
                title: '连接中...',
                mask: true,
            });
        } else {
            current.toast.show({
                title: "连接中..."
            })
        }

        let params = [];
        Object.keys(socketData).forEach(o => {
            params.push(o + "=" + socketData[o])
        });
        return new Promise((resolve, reject) => {
            wx.connectSocket({
                url: config.orderSystem.socket + "?" + params.join("&"),
            })
            wx.onSocketOpen(function () {
                status = 1;
                clearInterval(heartId);
                heartId = setInterval(() => {
                    this.send({
                        msg: "我还活着"
                    }, "heart");
                }, 10000);
                console.log("------socket已连接------");
                resolve();
                if (wx.canIUse("hideLoading")) {
                    wx.hideLoading()
                } else {
                    current.toast.hide();
                }

            }.bind(this));
            wx.onSocketError(function (res) {
                status = 0;
                console.log("------socket无法连接------");
                clearInterval(heartId);
                if (wx.canIUse("showToast.object.image'")) {
                    wx.showToast({
                        title: '连接失败',
                        image: "/assets/icon/fail.png",
                        duration: 3000
                    })
                } else {
                    current.toast.show({
                        title: "连接失败"
                    })
                }

                reject();
            })


            wx.onSocketClose(res => {
                status = 0;
                clearInterval(heartId);
                console.log("socket已关闭");
            });
            this.setupEvent();
        });
    }

    getStatus() {
        return status;
    }

    //初始化事件
    setupEvent() {
        wx.onSocketMessage(data => {
            var obj = JSON.parse(data.data);
            console.log("消息已到达：", obj);
            this.emit(obj.code, obj.data);
        })
    }

    //向socket发送消息
    send(msg, method) {

        var f = function () {
            var sendData = {
                method: method,
                data: msg,
            };
            console.log("发送消息：", sendData);
            wx.sendSocketMessage({
                data: JSON.stringify({
                    'data': msg,
                    'method': method,
                }),
            })

        }.bind(this);
        if (status === 0) {
            this.open(socketData).then(() => {
                f()
            })
        } else {
            f();
        }

    }
}

module.exports = {
    Socket: Socket,
    // Event: SocketEvent
};